package com.mms.utsc.smartnet;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.concurrent.ExecutionException;

import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.database.SQLException;
import android.widget.RemoteViews;

public class SmartNetWidget extends AppWidgetProvider {
	// receiver

	@Override
	public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
		// TODO Auto-generated method stub
		// updated every 30 min
		// get package name from context => refer to other intents

		// super.onUpdate(context, appWidgetManager, appWidgetIds);

		// N is how many different appWidgetIds we need to refer to
		// ie. if more than one of these widgets exist
		final int N = appWidgetIds.length;
		for (int index = 0; index < N; index++) {
			int appWidgetId = appWidgetIds[index];
			RemoteViews view = new RemoteViews(context.getPackageName(), R.layout.widget);
			// tell the user the # of unread announcements
			DBHandler db = new DBHandler(null, context);
			try {
				db.updateAnnouncements();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ExecutionException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			ArrayList<Announcement> announcements = db.getLocalDBHandler().getAllAnnouncements(null);
			int numAnnouncements = announcements.size();
			if (numAnnouncements == 0) {
				view.setTextViewText(R.id.tvWidgetAnnouncements, "No unread announcements.");
			} else if (numAnnouncements == 1) {
				view.setTextViewText(R.id.tvWidgetAnnouncements, numAnnouncements + " unread announcement.");
			} else {
				view.setTextViewText(R.id.tvWidgetAnnouncements, numAnnouncements + " unread announcements.");
			}

			// tell the user when the next class is
			view.setTextViewText(R.id.tvWidgetNextClass, "at: ??? in: rm ???");
			// tell the user if there's anything that's due next class or some
			// reminder for next class (ie. bring something special)
			view.setTextViewText(R.id.tvWidgetNextClassLine2, trimStrToLength("Bring lab manual and something else.", 50, "..."));

			appWidgetManager.updateAppWidget(appWidgetId, view);
		}
	}

	static String trimStrToLength(String input, int length, String appendText) {
		if (length < appendText.length())
			return input;
		if (input.length() < length)
			return input;
		return input.replaceAll("(?<=.{12})\\b.*", appendText);
	}

	@Override
	public void onDeleted(Context context, int[] appWidgetIds) {
		// TODO Auto-generated method stub
		// drag widget into the trash can => this method is called
		super.onDeleted(context, appWidgetIds);
	}

}
